package com.hooview.common.utils;

import cn.jiguang.common.ClientConfig;
import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jpush.api.JPushClient;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Message;
import cn.jpush.api.push.model.Options;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.notification.AndroidNotification;
import cn.jpush.api.push.model.notification.IosAlert;
import cn.jpush.api.push.model.notification.IosNotification;
import cn.jpush.api.push.model.notification.Notification;
//import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class JpushClient {
    //在极光注册的APPKEY和MASTERSECRET    必填
    private static final String APPKEY = "8d04ea1b8f098f5d43770d0b";

    private static final String MASTERSECRET = "24279babcd15db91ee1784cf";

    private static JPushClient jpushClient = null;

    //保存离线的时长，最多支持10天     （Ps：不填写时，默认是保存一天的离线消息     0：代表不保存离线消息）
    private static int timeToLive = 60 * 60 * 24;

    private static Logger logger = LoggerFactory.getLogger(JpushClient.class);

    //微博自定义消息推送
    public static PushPayload buildPushObject(String title, String content, String type) {
        return PushPayload.newBuilder()
                .setPlatform(Platform.android_ios())
                .setAudience(Audience.all())
                .setMessage(Message.newBuilder()
                        .setMsgContent(content)
                        .setTitle(title)
                        .addExtra("type", type)
                        .build())
                .setOptions(
                        Options.newBuilder()
                                .setApnsProduction(true)
                                .setTimeToLive(timeToLive)
                                .build())
                .build();

    }

    //快讯推送通知
    public static PushPayload buildPushObject(String title, String content) {
        IosAlert alert = IosAlert.newBuilder()
                .setTitleAndBody(title, null, content)
                .build();
        return PushPayload.newBuilder()
                .setPlatform(Platform.all())
                .setAudience(Audience.all())
                .setNotification(Notification.newBuilder()
                        .addPlatformNotification(
                                AndroidNotification.newBuilder()
                                        .addExtra("type", "infomation")
                                        .setTitle(title)
                                        .setAlert(content)
                                        .build())
                        .addPlatformNotification(IosNotification.newBuilder()
                                .addExtra("type", "infomation")
                                .setAlert(alert)
                                .build())
                        .build())
                .setOptions(Options.newBuilder()
                        .setApnsProduction(true)//true-推送生产环境 false-推送开发环境（测试使用参数）
                        .setTimeToLive(timeToLive)//消息在JPush服务器的失效时间（测试使用参数）
                        .build())
                .build();
    }

    //快讯推送通知
    public static PushPayload buildPushObjectByAlias(String title, String content,String alias) {
        IosAlert alert = IosAlert.newBuilder()
                .setTitleAndBody(title, "收到新消息", content)
                .build();
        return PushPayload.newBuilder()
                .setPlatform(Platform.all())
                .setAudience(Audience.alias(alias))
                .setNotification(Notification.newBuilder()
                        .addPlatformNotification(
                                AndroidNotification.newBuilder()
                                        .addExtra("type", "infomation")
                                        .setTitle(title)
                                        .setAlert(content)
                                        .build())
                        .addPlatformNotification(IosNotification.newBuilder()
                                .addExtra("type", "infomation")
                                .setAlert(alert)
                                .build())
                        .build())
                .setOptions(Options.newBuilder()
                        .setApnsProduction(true)//true-推送生产环境 false-推送开发环境（测试使用参数）
                        .setTimeToLive(timeToLive)//消息在JPush服务器的失效时间（测试使用参数）
                        .build())
                .build();
    }



    //消息推送（ sign 0：快讯通知，1：微博消息推送 , 2:别名通知）
    public static void sendPush(String title, String content, Integer sign, String type) {
        try {
            jpushClient = new JPushClient(MASTERSECRET, APPKEY, null, ClientConfig.getInstance());
            if (StringUtils.isBlank(type)) type = "JPush";
            //生成推送的内容
            PushPayload payload = null;
            if (sign == 0)
                payload = buildPushObject(title, content);//快讯通知 全体
            else if(sign == 1)
                payload = buildPushObject(title, content, type); //消息推送全体
            else if(sign == 2)
                payload = buildPushObjectByAlias(title,content,type); //别名通知单个
            PushResult result = jpushClient.sendPush(payload);
            logger.info("-----极光推送成功-----");
            logger.info("Got result - " + result);
        } catch (APIConnectionException e) {
            // Connection error, should retry later
            logger.error("Connection error, should retry later", e);

        } catch (APIRequestException e) {
            // Should review the error, and fix the request
            logger.error("Should review the error, and fix the request", e);
            logger.info("HTTP Status: " + e.getStatus());
            logger.info("Error Code: " + e.getErrorCode());
            logger.info("Error Message: " + e.getErrorMessage());
        }
    }

    public static void main(String[] args) throws APIConnectionException, APIRequestException {
//        String s = "{title:"+title+",body:"+content+"}";
        sendPush("测试标题ios", "测试内容ios", 0, "测试");
    }

}
